package com.feeyin.radar.crm.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

import com.feeyin.radar.commons.FileUtils;
import com.feeyin.radar.commons.Page;
import com.feeyin.radar.commons.StringUtils;
import com.feeyin.radar.crm.dao.ContractCaseDAO;
import com.feeyin.radar.crm.dao.ContractCaseTypeDAO;
import com.feeyin.radar.crm.dao.ContractDAO;
import com.feeyin.radar.crm.dao.ContractSubCaseDAO;
import com.feeyin.radar.crm.dao.ProcessDAO;
import com.feeyin.radar.crm.dao.ProcessGroupDAO;
import com.feeyin.radar.crm.model.CaseAttach;
import com.feeyin.radar.crm.model.CaseProcessDiagram;
import com.feeyin.radar.crm.model.ContractCase;
import com.feeyin.radar.crm.model.ContractCaseType;
import com.feeyin.radar.crm.model.ContractDetail;
import com.feeyin.radar.crm.model.ProcessGroup;
import com.feeyin.radar.crm.model.SubContractCase;
import com.feeyin.radar.crm.service.ContractCaseService;
import com.feeyin.radar.sys.service.UserService;
import com.feeyin.radar.crm.model.Process;
public class ContractCaseServiceImpl implements ContractCaseService{

	private ContractCaseTypeDAO contractCaseTypeDAO;
	private ProcessGroupDAO processGroupDAO;
	private ProcessDAO processDAO;
	private ContractSubCaseDAO contractSubCaseDAO;
	private ContractCaseDAO contractCaseDAO;
    private ContractDAO contractDAO;
    private UserService userService;
	public ContractCaseType getCaseType(String caseCode) {
		
		ContractCaseType caseType = contractCaseTypeDAO.getCaseType(caseCode);
		ProcessGroup group =processGroupDAO.getGroupById(caseType.getGroupId());
//		List<com.feeyin.radar.crm.model.Process> processList = processDAO.getProcessListByGroupId(group.getId().longValue());
//		group.setProcessList(processList);
		caseType.setProcessGroup(group);
		// TODO Auto-generated method stub
		return caseType;
	}


	public void setProcessGroupDAO(ProcessGroupDAO processGroupDAO) {
		this.processGroupDAO = processGroupDAO;
	}

	public void setProcessDAO(ProcessDAO processDAO) {
		this.processDAO = processDAO;
	}


	public void setContractCaseTypeDAO(ContractCaseTypeDAO contractCaseTypeDAO) {
		this.contractCaseTypeDAO = contractCaseTypeDAO;
	}


	public void setContractSubCaseDAO(ContractSubCaseDAO contractSubCaseDAO) {
		this.contractSubCaseDAO = contractSubCaseDAO;
	}
/**
 * 封装VO便于页面展示
 * @param caseObj
 * @return
 * @throws IllegalAccessException
 */
	public ContractDetail packContractDetail(Object caseObj){
		ContractDetail cd = new ContractDetail();
		if(caseObj instanceof ContractCase){
			cd.setSuffixCaseName(((ContractCase)caseObj).getSuffixCaseName());
			cd.setContractCaseName(((ContractCase)caseObj).getContractCaseFullName());
			cd.setCaseCode(((ContractCase)caseObj).getCaseCode());
			cd.setApplicationCode(((ContractCase)caseObj).getApplicationCode());
			cd.setDescription(((ContractCase)caseObj).getDescription());
			cd.setProcessName(((ContractCase)caseObj).getProcessName());
			cd.setTypeId(((ContractCase)caseObj).getContractCaseType().getId());
			cd.setProcessId(((ContractCase)caseObj).getProcessId());
			cd.setProcessGroupId(((ContractCase)caseObj).getProcessGroupId());
			cd.setCostValue(BigDecimal.valueOf(((ContractCase)caseObj).getCostValue()));
			cd.setOfficialCost(BigDecimal.valueOf(((ContractCase)caseObj).getOfficialCost()));
			cd.setOperationCost(BigDecimal.valueOf(((ContractCase)caseObj).getOperationCost()));
			cd.setProxyCost(BigDecimal.valueOf(((ContractCase)caseObj).getProxyCost()));
			cd.setMark(((ContractCase)caseObj).getMark());
			cd.setApplicationDate(((ContractCase)caseObj).getApplicationDate());
			cd.setIsSub(0L);
			cd.setCaseId(((ContractCase)caseObj).getId());
			cd.setModifyDate(((ContractCase)caseObj).getModifyDate());
			cd.setContractId(Integer.valueOf(((ContractCase)caseObj).getContractId()));
			cd.setTypeName(((ContractCase)caseObj).getCaseTypeName());
		}else if(caseObj instanceof SubContractCase){
			cd.setSuffixCaseName(((SubContractCase)caseObj).getSuffixCaseName());
			cd.setContractCaseName("");
			cd.setCaseCode("");
			cd.setApplicationCode(((SubContractCase)caseObj).getApplicationCode());
			cd.setApplicationDate(((SubContractCase)caseObj).getApplicationDate());
			cd.setDescription(((SubContractCase)caseObj).getDescription());
			cd.setProcessName("");
			cd.setTypeId(((SubContractCase)caseObj).getTypeId());
			cd.setCostValue(BigDecimal.valueOf(((SubContractCase)caseObj).getCostValue()));
			cd.setOfficialCost(BigDecimal.valueOf(((SubContractCase)caseObj).getOfficialCost()));
			cd.setOperationCost(BigDecimal.valueOf(((SubContractCase)caseObj).getOperationCost()));
			cd.setProxyCost(BigDecimal.valueOf(((SubContractCase)caseObj).getProxyCost()));
			cd.setMark(((SubContractCase)caseObj).getMark());
			cd.setIsSub(1L);
			cd.setCaseId(((SubContractCase)caseObj).getId());
			cd.setModifyDate(((SubContractCase)caseObj).getModifyDate());
		}
	return cd;
	}
	public List<ContractDetail> convertContractCaseInfoIntoVO(Long contractId){
		List<ContractDetail> detailList = new ArrayList<ContractDetail>();
		List<ContractCase> caseList = getContractCaseInfo(contractId);
		if(caseList.isEmpty())
			return detailList;
		for(ContractCase case1:caseList){
			
			ContractDetail mainCase = packContractDetail(case1);
			String mark = mainCase.getCaseCode()+"_"+mainCase.getTypeId();
			mainCase.setMark(mark);
			mainCase.setContractId(contractId.intValue());
			detailList.add(mainCase);
			mainCase.setHasSub(1L);
			if(case1.getSubCaseList().isEmpty())
				continue;
			for(SubContractCase subCase:case1.getSubCaseList()){
				subCase.setContractCase(case1);
				ContractDetail subDetail =  packContractDetail(subCase);
				subDetail.setMark("sub_"+mark);
				subDetail.setContractId(contractId.intValue());
				detailList.add(subDetail);
			}
		}
		for(ContractDetail detail:detailList){
			System.out.println("**************************");
			System.out.println(detail.toString());
			System.out.println("**************************");
		}
		return detailList;
	}
	/**
	 * 得到 ContractCase和其下的子Case
	 * @param contractId
	 * @return
	 */
	public List<ContractCase> getContractCaseInfo(Long contractId){
		List<ContractCase> caseList = contractCaseDAO.getContractCasesByContractCode(contractId.toString());
		if(caseList==null||caseList.isEmpty())
			return new ArrayList<ContractCase>();
		//得到子CASE
		for(ContractCase case1:caseList){
			List<SubContractCase> subList = contractSubCaseDAO.getSubCaseList(case1.getId().longValue());
			if(subList.isEmpty())
				continue;
			case1.setSubCaseList(subList);
		}
		return caseList;
	}

	
	
	public List<com.feeyin.radar.crm.model.Process> getProcessListByGroupId(Long groupId){
		return processDAO.getProcessListByGroupId(groupId);
	}
	  public String getStoredPath(String basePath)
	  {
	    String storedPath = basePath + "upload" + System.getProperty("file.separator") + 
	      "contractCase" + System.getProperty("file.separator");
	    File file = new File(storedPath);
	    if ((file.exists()) && (file.isDirectory()))
	    {
	      return storedPath;
	    }
	    file.mkdirs();
	    return storedPath;
	  }
	  public String getStoredRelativePath(Long caseId)
	  {
	    String storedPath = "upload" + System.getProperty("file.separator") + 
	      "contractCase" + System.getProperty("file.separator") + "_" + caseId;
	    File file = new File(storedPath);
	    if ((file.exists()) && (file.isDirectory()))
	    {
	      return storedPath;
	    }
	    file.mkdirs();
	    return storedPath;
	  }

	public Long saveCaseAttach(String realPath,MultipartFile multipartFile,Long caseId,Long isSub){
		if(!StringUtils.isEmpty(realPath) 
				&& multipartFile != null && !multipartFile.isEmpty()){
			String fileName = multipartFile.getOriginalFilename();
//			String storedPath = getStoredPath(realPath) 
//									+ System.getProperty("file.separator") + fileName;
			String storedPath = getStoredPath(realPath) + fileName;
			boolean result2 = false;
			result2 = FileUtils.saveFile(storedPath, multipartFile);
			if(result2){
				if(caseId!=null){
					Map uppMap = new HashMap();
					uppMap.put("caseId", caseId);
					uppMap.put("isSub", isSub);
					//contractCaseDAO.delAttachCase(uppMap);
				}
				CaseAttach ca = new CaseAttach(caseId, storedPath, fileName, isSub);
			    Long id = contractCaseDAO.saveAttachCase(ca);
			    return id;
			}
		}
		return null;
	}
	
	public Long getMyContractCaseOrDeptsCount(Map paraMap){
		return contractCaseDAO.getContractCaseByUser_id_Dept_Count(paraMap);
	}

	public List<ContractDetail>  getMyContractCaseOrDepts(Map paraMap,Page page){
		
      //  contractCaseDAO.getContractCaseByUser_id_Dept_Count(paraMap);
	   List<ContractDetail> detailList = new ArrayList<ContractDetail>();
       List<Map> resultMapList =  (List<Map>)contractCaseDAO.getContractCaseByUser_id_Dept(paraMap,page);
       if(resultMapList==null||resultMapList.isEmpty())
    	   return detailList;
       
       for(Map resultMap:resultMapList){
    	   ContractCase mainCase = new ContractCase(resultMap);
    	   mainCase.setContractCaseType(contractCaseTypeDAO.getCaseType(mainCase.getType()));
    	   //mainCase.setProcess(processDAO.getProcessById(mainCase.getProcessId().longValue()));
    	   ContractDetail parentDetail = packContractDetail(mainCase);
    	   setExtensionCaseInfo(parentDetail,resultMap,false);
    	   detailList.add(parentDetail);
    	   List<SubContractCase> subList = contractSubCaseDAO.getSubCaseList(mainCase.getId().longValue());
			if(subList.isEmpty())
				continue;
			parentDetail.setHasSub(1L);
			mainCase.setSubCaseList(subList);
			for(SubContractCase subCase:subList){
				subCase.setContractCase(mainCase);
				ContractDetail subDetail = packContractDetail(subCase);
				setExtensionCaseInfo(subDetail,resultMap,true);
				detailList.add(subDetail);
			}
       }
		return detailList;
	}
	
	public void setExtensionCaseInfo(ContractDetail detail,Map resultMap,boolean isSub){
		/*b.contractCode as contractCode,
		(select userName from rone.users where id = b.applyPersonId) as applyName,
		(select userName from rone.users where id = b.salePersonId) as saleName,
		c.processName as processName,
		c.processTime as processTime*/
		detail.setContractCode(resultMap.get("contractCode").toString());
		detail.setApplyName(resultMap.get("applyName").toString());
		detail.setSaleName(resultMap.get("saleName").toString());
		detail.setApplyPersonId(Long.valueOf(resultMap.get("applyPersonId").toString()));
		if(!isSub){
			detail.setProcessTime(Integer.valueOf(resultMap.get("processTime").toString()));
			detail.setProcessName(resultMap.get("processName").toString());
		}
		
	}
	@Override
	public ContractDetail getSingleContractCaseToView(Integer caseId){
		Map paraMap = new HashMap();
		paraMap.put("caseId", caseId);
		Map resultMap = ((List<Map>)contractCaseDAO.getContractCaseByUser_id_Dept(paraMap,null)).get(0);
		ContractCase mainCase = new ContractCase(resultMap);
		mainCase.setContractCaseType(contractCaseTypeDAO.getCaseType(mainCase.getType()));
   	   //mainCase.setProcess(processDAO.getProcessById(mainCase.getProcessId().longValue()));
   	    ContractDetail parentDetail = packContractDetail(mainCase);
   	    setExtensionCaseInfo(parentDetail,resultMap,false);
		return parentDetail;
	}
	@Override
	public List<CaseProcessDiagram> getProcessDiagram(Long processGroupId,Long processId){
		List<Process> processList = processDAO.getProcessListByGroupId(processGroupId);
		List<CaseProcessDiagram> flowList = new ArrayList<CaseProcessDiagram>();
		boolean isBingo = false;
		List<Process>crossesList = new ArrayList<Process>();
		for(Process process:processList){
            if(isBingo){
				if(!process.getIsNecessary()){
					crossesList.add(process);
				}else{
					CaseProcessDiagram a = new CaseProcessDiagram(process,"0");
					if(!crossesList.isEmpty())
						a.setCrossProcess(crossesList);
					flowList.add(a);
					break;
				}
			}
			if(process.getId().intValue()==processId.intValue()){
				isBingo=true;
				 CaseProcessDiagram a = null;
				if(process.getIndexFlag().intValue()==1)
					 a = new CaseProcessDiagram(process,null);
				else
				     a = new CaseProcessDiagram(process,"1");
				flowList.add(a);
			}
				
			if(!isBingo){
			   if(process.getIsNecessary()){
				   CaseProcessDiagram a = null;
				   if(process.getIndexFlag().intValue()==1)
						 a = new CaseProcessDiagram(process,null);
					else
					     a = new CaseProcessDiagram(process,"1");
					flowList.add(a);
			   }
			}
		}
		return flowList;
	}
	@Override
	public List<CaseAttach>getCaseAttach(Long caseId ,boolean isSub){
		List<CaseAttach> list = contractCaseDAO.getCaseAttach(caseId, isSub);
		if(list==null)
			list = new ArrayList<CaseAttach>();
		return list;
	}
	 
	public void setContractCaseDAO(ContractCaseDAO contractCaseDAO) {
		this.contractCaseDAO = contractCaseDAO;
	}


	public void setContractDAO(ContractDAO contractDAO) {
		this.contractDAO = contractDAO;
	}


	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
